package slowka;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;

/**
 *
 * @author ssobczak
 */
public class TimerThread implements Runnable {
    public TimerThread(JLabel tlabel, ActionListener c) {
        timeLabel= tlabel;
        callback = c;
        secLeft = 0;
        wtd = WhatToDo.ignore;
    }

    public void run() {
        while(secLeft != 0) {
            secLeft--;
            drawClock();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {}
                switch(wtd) {
                    case finish:
                        return;
                    case wait:
                        synchronized(this) {
                        try {
                            wait();
                        } catch (InterruptedException ex1) {}
                        wtd = WhatToDo.ignore;
                        }
                        break;
                    case ignore:
            }
        }

        timeLabel.setForeground(Color.red);
        callback.actionPerformed(new ActionEvent(this, 0, ""));
    }

    private void drawClock() {
        timeLabel.setText(new Integer(secLeft).toString());
    }

    public enum WhatToDo { ignore, finish, wait } ;

    private int secLeft;
    private JLabel timeLabel;
    private ActionListener callback;
    private WhatToDo wtd;

    public synchronized void restart(int left) {
        secLeft = left;
        timeLabel.setForeground(Color.black);
        wtd = WhatToDo.ignore;

        drawClock();
    }

    public synchronized void setNextAction(WhatToDo w) {
        wtd = w;
    }
}
